package com.wdc.controller.admin;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.wdc.context.BaseContext;
import com.wdc.context.UserConstant;
import com.wdc.mapper.AdminMapper;
import com.wdc.model.domain.User;
import com.wdc.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/user")
@Slf4j
public class AdminController {

    @Autowired
    private AdminMapper adminMapper;

    @Autowired
    private UserService userService;


    /**
     * 查询用户
     * @param userAccount
     * @return
     */
    @GetMapping("/search")
    public List<User>  searchUsers(String userAccount, HttpServletRequest request){
        //获取当前role
        if (!isAdmin(request)) {
            return null;
        }

        if (userAccount == null){
            return null;
        }
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.like("userAccount", userAccount);
        List<User> userList = adminMapper.selectList(queryWrapper);
        return userList.stream().map(user -> userService.getSafetyUser(user)).collect(Collectors.toList());


    }

    @PostMapping("/delete")
    public boolean deleteUser( Integer id, HttpServletRequest request){
        if (!isAdmin(request)) {
            return false;
        }
        if (id <= 0){
            return false;
        }

        return userService.removeById(id);
    }



    /**
     * 是否是管理员
     * @param request
     * @return
     */
    private boolean isAdmin(HttpServletRequest request){
        Object userObj = request.getSession().getAttribute(UserConstant.USER_LOGIN_STATE);
        User user = (User)userObj;
        return user.getRole() == 1;
    }
}
